package com.whitedust.top20;

import com.whitedust.structure.ListNode;
import com.whitedust.structure.TreeNode;

/**
 * @author A
 * @since 2025/11/3 15:27
 */

public class Top20 {
    //指定范围反转链表
    public ListNode reverseBetween(ListNode head, int left, int right) {
        //pre cur end next 四部曲
        ListNode dummy = new ListNode(0, head);
        for (int i = 1; i < left; i++) {
            dummy = dummy.next;
        }
        ListNode pre = dummy;
        ListNode start = dummy.next;
        for (int i = 0; i < right - left + 1; i++) {
            dummy = dummy.next;
        }
        ListNode end = dummy;
        ListNode next = dummy.next;
        end.next = null;
        pre.next = reverse(start);
        start.next = next;
        //注意当头节点也反转的时候，返回的节点应该修改
        if (left == 1) return end;
        return head;
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
